package com.horay.nettydemo.nio.buffer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.unit.DataSize;

import java.nio.ByteBuffer;

/**
 * 只读Buffer
 *
 * @author heyingcheng
 * @date 2019/11/23 23:16
 */
@Slf4j
public class ReadOnlyBuffer {

    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(Math.toIntExact(DataSize.ofBytes(64L).toBytes()));
        for (int i = 0; i < 5; i++) {
            byteBuffer.put((byte) i);
        }

        byteBuffer.flip();

        while (byteBuffer.hasRemaining()) {
            log.info("1-value:[{}]", byteBuffer.get());
        }

        byteBuffer.clear();
        byteBuffer.put((byte) 6);
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            log.info("2-value:[{}]", byteBuffer.get());
        }

        byteBuffer.clear();
        ByteBuffer readOnlyByteBuffer = byteBuffer.asReadOnlyBuffer();
        byteBuffer.put((byte) 7);
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            log.info("3-value:[{}]", byteBuffer.get());
        }

        readOnlyByteBuffer.put((byte) 8);
    }

}
